//
//  reportDetailViewController.m
//  阿帕
//
//  Created by mac on 2020/1/6.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "ReportDetailViewController.h"
#import "CYPlaceholderTextView.h"
#import "TZImagePickerController.h"
#import "ZXCollectionCell.h"

@interface ReportDetailViewController ()<ZXCollectionCellDelegate, TZImagePickerControllerDelegate, UICollectionViewDataSource,UICollectionViewDelegate>
@property (weak, nonatomic) IBOutlet UILabel *weiXiuTextLabel;
@property (weak, nonatomic) IBOutlet UILabel *applyTextLabel;
@property (weak, nonatomic) IBOutlet UILabel *imgTextLabel;
@property (weak, nonatomic) IBOutlet UIView *detailBgView;
@property (weak, nonatomic) IBOutlet UIView *imgBgView;
@property (weak, nonatomic) IBOutlet UITextField *priceTextField;
@property (strong , nonatomic)CYPlaceholderTextView *textView;
@property (weak, nonatomic) IBOutlet UIView *hLine;
@property (weak, nonatomic) IBOutlet UIView *hLine2;
@property (strong , nonatomic)UIButton *addCardButton;

@property (nonatomic,strong) NSMutableArray *imageArr;
@property (nonatomic,strong) NSMutableArray *imageUrlArray;
@property (nonatomic,strong) UICollectionView *collectionView;

@end

@implementation ReportDetailViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = BackgroundColor;
    
    self.navigationItem.title = @"维修详情上报";
    
    [self UIStyleSet];
    
    UIView *textBgView = [[UIView alloc] initWithFrame:CGRectMake(15, _applyTextLabel.cy_bottom + 10, ScreenW-30, 80)];
    textBgView.backgroundColor = [UIColor cy_colorWithHexString:@"#F3F5F8"];
    [self.view addSubview:textBgView];
    
    _textView = [[CYPlaceholderTextView alloc] initWithFrame:CGRectMake(11, 8, textBgView.cy_width - 22, textBgView.cy_height - 16)];
    _textView.text = @"";
    _textView.textColor = Dark_TextColor;
    _textView.placeholder = @"请填写申请详情内容";
    _textView.placeholderColor = [UIColor cy_colorWithHexString:@"#B6BED2"];
    _textView.backgroundColor = [UIColor cy_colorWithHexString:@"#F3F5F8"];
    _textView.font = font(14);
    [textBgView addSubview:_textView];
    
    //    _textView = [[CYPlaceholderTextView alloc] initWithFrame:CGRectMake(10, _applyTextLabel.cy_bottom, ScreenW - 20, 80)];
    //    _textView.text = @"";
    //    cut(_textView, 5);
    //    cutBorder(_textView, 1, @"#F1F1F1");
    //    _textView.textColor = Light_TextColor;
    //    _textView.placeholder = @"请填写申请详情内容";
    //    _textView.placeholderColor = Light_TextColor;
    //    _textView.backgroundColor = [UIColor whiteColor];
    //    _textView.font = font(14);
    //    [_detailBgView addSubview:_textView];
    
    [self.view addSubview:self.addCardButton];
}

- (void)UIStyleSet {
    
    _weiXiuTextLabel.textColor = Dark_TextColor;
    _applyTextLabel.textColor = Dark_TextColor;
    _imgTextLabel.textColor = Dark_TextColor;
    _hLine.backgroundColor = BackgroundColor;
    _hLine2.backgroundColor = BackgroundColor;
    
    _priceTextField.textFieldType = CJTextFieldStringTypeMoneyValue;
    _priceTextField.maxLength = 12;
    
    NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:_weiXiuTextLabel.text];
    [attString addAttribute:(NSString*)NSForegroundColorAttributeName value:[UIColor redColor] range:[_weiXiuTextLabel.text rangeOfString:@"*"]];
    _weiXiuTextLabel.attributedText = attString;
    
    NSMutableAttributedString *attString2 = [[NSMutableAttributedString alloc] initWithString:_applyTextLabel.text];
    [attString2 addAttribute:(NSString*)NSForegroundColorAttributeName value:[UIColor redColor] range:[_applyTextLabel.text rangeOfString:@"*"]];
    _applyTextLabel.attributedText = attString2;
    
    NSMutableAttributedString *attString3 = [[NSMutableAttributedString alloc] initWithString:_imgTextLabel.text];
    [attString3 addAttribute:(NSString*)NSForegroundColorAttributeName value:[UIColor redColor] range:[_imgTextLabel.text rangeOfString:@"*"]];
    _imgTextLabel.attributedText = attString3;
    
    UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 40, ScreenW, _imgBgView.cy_height) collectionViewLayout:flowLayout];
    //设置代理
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [_imgBgView addSubview:self.collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    //注册cell和ReusableView（相当于头部）
    [self.collectionView registerClass:[ZXCollectionCell class] forCellWithReuseIdentifier:@"cell"];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.imageArr.count;
}
//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identify = @"cell";
    ZXCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
    [cell sizeToFit];
    if (!cell) {
        NSLog(@"无法创建CollectionViewCell时打印，自定义的cell就不可能进来了。");
    }
    if (indexPath.item == 0) {
        cell.close.hidden = YES;
    } else {
        cell.close.hidden = NO;
    }
    cell.imgView.image = [self.imageArr objectAtIndex:indexPath.row];
    cell.delegate = self;
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //边距占5*4=20 ，2个
    //图片为正方形，边长：(fDeviceWidth-20)/2-5-5 所以总高(fDeviceWidth-20)/2-5-5 +20+30+5+5 label高20 btn高30 边
    return CGSizeMake((ScreenW-20)/4, (ScreenW-20)/4);
}
//定义每个UICollectionView 的间距
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 5, 5, 5);
}
//定义每个UICollectionView 纵向的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}
#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    WEAKSELF
    
    NSLog(@"选择%ld",indexPath.row);
    if (indexPath.item == 0) {
        
        if (self.imageArr.count == 10) {
            [XSInfoView showInfo:@"最多可上传9张图片" onView:self.view];
        } else {
            [SystemPermissionsToolObject determineLatestPermissionsOfTheLocalAlbum];
            
            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
            imagePickerVc.allowPickingVideo = NO;
            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
                [weakSelf.imageArr addObjectsFromArray:photos];
                [weakSelf.collectionView reloadData];
                
                [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@",[NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl],FILE_UPLOAD) file:photos fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
                    
                    [weakSelf.imageUrlArray addObject:response[@"data"]];
                    
                } failure:^(NSInteger code, NSString *msg) {
                    
                }];
                
            }];
            imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:imagePickerVc animated:YES completion:nil];
            
        }
        
    } else {
        
        //查看
        HZPhotoBrowser *browser = [[HZPhotoBrowser alloc] init];
        browser.isFullWidthForLandScape = YES;
        browser.isNeedLandscape = YES;
        browser.currentImageIndex = (int)(indexPath.item-1);
        browser.imageArray = weakSelf.imageUrlArray;
        [browser show];
    }
}
//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)moveImageBtnClick:(ZXCollectionCell *)aCell{
    NSIndexPath * indexPath = [self.collectionView indexPathForCell:aCell];
    NSLog(@"删除了第%ld个图片",indexPath.row);
    [self.imageArr removeObjectAtIndex:indexPath.row];
    [self.imageUrlArray removeObjectAtIndex:indexPath.row-1];
    [self.collectionView reloadData];
}

#pragma mark -- 上报
- (void)btnEventClick {
    WEAKSELF
    if ([DCSpeedy isBlankString:_priceTextField.text] == YES || [DCSpeedy isBlankString:_textView.text] == YES || self.imageUrlArray.count == 0) {
        [XSInfoView showInfo:@"必填信息不能为空" onView:self.view];
        return;
    }
    
    NSString *arrStr = [self.imageUrlArray componentsJoinedByString:@","];
    
    NSDictionary *parmas = @{
        @"reportCompleteFee": _priceTextField.text,
        @"reportCompleteDetails": _textView.text,
        @"reportCompleteImgs": arrStr,
        @"code": _code,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager putNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], VEHICLEREPAIRAPPLY_REPORT) withParameter:parmas withVC:self netName:@"维修完成上报" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:@"维修上报成功" onView:weakSelf.view];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
            [weakSelf.navigationController popViewControllerAnimated:YES];
        });
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

- (UIButton *)addCardButton {
    if (!_addCardButton) {
        _addCardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_addCardButton setTitle:@"上报" forState:UIControlStateNormal];
        _addCardButton.titleLabel.font = font(16);
        cut(_addCardButton, BTN_BORDER_RADIUS);
        [_addCardButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_addCardButton setBackgroundColor:Theme_ColorValue];
        [_addCardButton addTarget:self action:@selector(btnEventClick) forControlEvents:UIControlEventTouchUpInside];
        _addCardButton.frame = CGRectMake(20, ScreenH - NavHeight - MenuBarHeight - 65, ScreenW-40, 45);
    }
    return _addCardButton;
}
- (NSMutableArray *)imageArr {
    if (!_imageArr) {
        _imageArr = [[NSMutableArray alloc] initWithObjects:image(@"gcy_icon_add_photo"), nil];
    }
    return _imageArr;
}
- (NSMutableArray *)imageUrlArray {
    if (!_imageUrlArray) {
        _imageUrlArray = [[NSMutableArray alloc] init];
    }
    return _imageUrlArray;
}
@end
